package com.msl.debezium.common;

import com.msl.debezium.validate.Phone;
import com.msl.debezium.validate.PhoneValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    ApplicationContext appContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.appContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Class<Phone> phClass = Phone.class;
        Map<String, Object> annoBeans = appContext.getBeansWithAnnotation(phClass);
        for(Map.Entry<String, Object> entry : annoBeans.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            log.info("=========="+clazz.getName());
            //Phone phone = AnnotationUtils.findAnnotation(clazz, phClass);

            Field[] fields = clazz.getDeclaredFields();
            for(Field field : fields){
                Phone phone = AnnotationUtils.findAnnotation(field, phClass);
                if(phone != null){
                    PhoneValidate va = new PhoneValidate();
                    String name = field.getName();

                }
            }
        }
    }
}
